package com.unisound.tracelog.client.core.support.pool;

import com.unisound.tracelog.client.core.properties.TraceLogClientProperties;
import com.unisound.tracelog.client.core.util.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

public class TraceLogDiscardOldestPolicy implements RejectedExecutionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(TraceLogDiscardOldestPolicy.class);

    private TraceLogClientProperties traceLogClientProperties = SpringUtil.getBean(TraceLogClientProperties.class);

    @Override
    public void rejectedExecution(Runnable newTask, ThreadPoolExecutor e) {
        if (!e.isShutdown()) {
            Runnable oldTask = e.getQueue().poll();
            e.execute(newTask);

            if (traceLogClientProperties.isLogEnable()) {
                LOGGER.info("TraceLog任务被拒绝. 丢弃旧任务={} 执行新任务={}", oldTask, newTask);
            }
        } else {
            if (traceLogClientProperties.isLogEnable()) {
                LOGGER.info("TraceLog任务被拒绝. 执行任务={} 原因:线程池已关闭", newTask);
            }
        }
    }
}
